<template>
  <el-card shadow="never">
    <el-row>
      <el-col :span="1.5" style="margin-bottom: 10px;">
        <el-button type="primary" plain @click="togglePuttingMode">
          {{ isPuttingMode ? '退出摆放设备' : '摆放设备' }}
        </el-button>
        <el-button type="warning" plain class="addDeviceToGroup" @click="startRemovingDevice" :disabled="isPuttingMode">
          移除设备
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <div class="middle" @click="handleMapClick" ref="middleContainer">
        <div v-if="isPuttingMode" class="putting-tip">请点击图片选择设备摆放位置</div>

        <img :src="backgroundImage" alt="" ref="mapImage" @load="onImageLoad" />
        
        <div 
          v-for="device in deviceData" 
          :key="device.id"
          class="device-icon"
          :style="{ 
            left: (device.posx * 100) + '%', 
            top: (device.posy * 100) + '%' 
          }"
        >
          <img :src="device.iconPath" alt="设备" />
          <span class="device-name">{{ device.deviceCustomName || device.deviceName }}</span>
        </div>
      </div>
    </el-row>
  </el-card>
  
  <!-- 设备对话框（共用） -->
  <el-dialog
    :title="dialogMode === 'put' ? '选择设备' : '选择要移除的设备'"
    v-model="dialogVisible"
    width="900px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-table
      :data="dialogDevices"
      bordered
      v-loading="isLoading"
    >
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="设备自定义名称" prop="deviceCustomName">
        <template #default="scope">
          {{ scope.row.deviceCustomName || '未定义' }}
        </template>
      </el-table-column>
      <el-table-column label="产品" prop="productKey" width="180">
        <template #default="scope">
          {{ getProductName(scope.row.productKey) }}
        </template>
      </el-table-column>
      <el-table-column label="设备DN" prop="deviceName" />
      <el-table-column label="状态" prop="online" align="center" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.online" type="success" size="small">在线</el-tag>
          <el-tag v-else type="danger" size="small">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template #default="scope">
          <el-button 
            link 
            :type="dialogMode === 'put' ? 'primary' : 'danger'" 
            :icon="dialogMode === 'put' ? 'Check' : 'Delete'" 
            @click="dialogMode === 'put' ? handleSubmit(scope.row) : handleRemoveDevice(scope.row)"
          >
            {{ dialogMode === 'put' ? '确认' : '移除' }}
          </el-button>
        </template>
      </el-table-column> 
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getSpaceDevices, spaceSaveDevice } from './api/building.api'
import { getProductsList, IProductsVO } from '../device/api/products.api'
import { listByIds } from '@/api/system/oss'
import { devicePropertyLogs } from '../device/api/devices.api'
// 引入公共方法获取设备属性、判断是否为灯控设备和网关
import { getDeviceProperties, isLightController, getDeviceIconPath } from '@/utils/deviceUtils'

const route = useRoute()
const { id, ossId } = route.params

const backgroundImage = ref<string>('') // 背景图片URL
const mapImage = ref<HTMLImageElement | null>(null) // 图片元素引用
const middleContainer = ref<HTMLDivElement | null>(null) // 容器元素引用
const isPuttingMode = ref(false) // 是否处于摆放模式
const selectedPosition = reactive({ x: 0, y: 0, percentX: 0, percentY: 0 }) // 选择的位置
// const defaultIcon = ref(TurnedOffLight) // 默认图标

// 对话框状态
const dialogVisible = ref(false)
const dialogMode = ref<'put' | 'remove'>('put') // 对话框模式：put-摆放设备，remove-移除设备
const dialogDevices = ref<any[]>([]) // 对话框中显示的设备列表
const isLoading = ref(false)

// 设备状态查询相关
const stateDialog = reactive({
  swName: '',
  slName: '',
  historyTime: [new Date(Date.now() - 24 * 60 * 60 * 1000), new Date()] as Date[], // 默认查询最近24小时
})

// 图片加载完成事件
const onImageLoad = () => {
  // 如果设备数据已经加载，重新处理设备位置
  if (deviceData.value.length > 0 && mapImage.value) {
    // 处理所有设备的位置信息
    deviceData.value = deviceData.value.map(device => processDevicePosition(device))
  }
}

// 开关历史数据查询
const swHistory = (device: any) => {
  if (!stateDialog.swName) return Promise.resolve(0)
  
  const end = stateDialog.historyTime[1]
  const start = stateDialog.historyTime[0]
  
  return devicePropertyLogs({
    deviceId: device.deviceId,
    name: stateDialog.swName,
    start: start.getTime(),
    end: end.getTime(),
  }).then((res) => {
    if (res.data && res.data.length > 0) {
      return Number(res.data[0].value)
    } else {
      return 0
    }
  }).catch(() => {
    return 0
  })
}

// 切换摆放模式
const togglePuttingMode = () => {
  if (isPuttingMode.value) {
    isPuttingMode.value = false
    ElMessage.info('已退出摆放模式')
  } else {
    isPuttingMode.value = true
    ElMessage.info('请点击图片选择设备摆放位置')
  }
}

// 进入移除设备模式
const startRemovingDevice = () => {
  dialogMode.value = 'remove'
  dialogVisible.value = true
  // 获取并过滤已摆放的设备
  getDevicesForDialog()
}

// 处理图片点击，记录位置信息
const handleMapClick = (event: MouseEvent) => {
  if (!isPuttingMode.value || !mapImage.value) return
  
  const rect = mapImage.value.getBoundingClientRect()
  // 记录点击的像素位置
  selectedPosition.x = event.clientX - rect.left
  selectedPosition.y = event.clientY - rect.top
  
  // 计算百分比位置
  selectedPosition.percentX = selectedPosition.x / rect.width
  selectedPosition.percentY = selectedPosition.y / rect.height

  dialogMode.value = 'put'
  dialogVisible.value = true
  getDevicesForDialog()
}

// 获取对话框显示的设备列表
const getDevicesForDialog = () => {
  isLoading.value = true
  getSpaceDevices(id)
  .then((res) => {
    if (res.code === 200) {
      const allDevices = res.data || []
      if (dialogMode.value === 'remove') {
        // 移除设备模式：过滤出有位置信息的设备
        dialogDevices.value = allDevices.filter(device => 
          device.posx && device.posy && 
          (device.posx !== 0 || device.posy !== 0)
        )
      } else {
        // 摆放设备模式：显示所有设备
        dialogDevices.value = allDevices
      }
    }
  })
  .finally(() => {
    isLoading.value = false
  })
}

// 移除设备
const handleRemoveDevice = async (device) => {
  try {
    // 将设备位置信息归零(使用百分比)
    await spaceSaveDevice({
      id: device.id,
      spaceId: id,
      posx: 0,
      posy: 0,
    })
    ElMessage.success('设备位置已移除')
    getDeviceList(id)
    getDevicesForDialog()
  } catch (error) {
    console.error('移除设备位置失败:', error)
    ElMessage.error('移除设备位置失败')
  }
}

// 更新设备图标状态
const updateDeviceIcons = async () => {
  // 对所有在线设备异步查询开关状态
  for (const device of deviceData.value) {
    // if (!device.productKey) {
    //   device.iconPath = ControlDevice
    //   continue
    // }
    const productKey = device.productKey
    
    // 网关设备直接设置图标
    // if (isGateway(productKey)) {
    //   device.iconPath = device.online ? OnlineGateway : OfflineGateway
    //   continue
    // }
    
    let switchState: number | undefined 
    // 灯控制器设备需要查询开关状态
    if (isLightController(productKey) && device.online) {
      const { swName, slName } = getDeviceProperties(productKey)
      stateDialog.swName = swName
      stateDialog.slName = slName
      try {
        switchState = await swHistory(device)
        // device.switchState = switchState
        // device.iconPath = switchState === 1 ? TurnedOnLight : TurnedOffLight
      } catch (error) {
        console.error('查询设备状态失败:', error)
        // device.iconPath = TurnedOffLight // 默认关灯状态
      }
    }
    // 调用公共方法获取图标路径
    device.iconPath = getDeviceIconPath(productKey, device.online, switchState)
    //  else if (isLightController(productKey) && !device.online) {
    //   device.iconPath = OfflineLight
    // } else {
    //   // 其他设备使用控制图标
    //   device.iconPath = ControlDevice
    // }
  }
}

// 查询已摆放的设备列表
const deviceData = ref<any[]>([])

const processDevicePosition = (device) => {
  if (device.posx > 1 || device.posy > 1) {
    // 由于我们使用百分比定位，需要将像素值转换为百分比
    if (mapImage.value) {
      const imgWidth = mapImage.value.naturalWidth || 1000; // 默认宽度
      const imgHeight = mapImage.value.naturalHeight || 1000; // 默认高度
      
      // 将像素坐标转换为百分比
      device.posx = device.posx / imgWidth;
      device.posy = device.posy / imgHeight;
      
      console.log('转换设备坐标为百分比:', device.id, device.posx, device.posy);
    }
  }
  device.posx = device.posx || 0;
  device.posy = device.posy || 0;
  
  return device;
};

// 修改 getDeviceList 函数，确保设备位置使用百分比
const getDeviceList = async (spaceId) => {
  try {
    const res = await getSpaceDevices(spaceId)
    if (res.code === 200) {
      // 过滤出有位置信息的设备
      const allDevices = res.data || []
      deviceData.value = allDevices
        .filter(device => 
          device.posx && device.posy && 
          (device.posx !== 0 || device.posy !== 0)
        )
        .map(device => processDevicePosition(device)) // 处理设备位置
      
      // 更新设备图标状态
      await updateDeviceIcons()
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
  }
}

// 确认添加设备
const handleSubmit = async (row) => {
  try {
    // 使用百分比位置保存
    await spaceSaveDevice({
      id: row.id,
      spaceId: id,
      posx: selectedPosition.percentX,
      posy: selectedPosition.percentY,
    })
    ElMessage.success('设备摆放成功')
    dialogVisible.value = false
    isPuttingMode.value = true
    getDeviceList(id)
  } catch (error) {
    console.error('摆放设备失败:', error)
    ElMessage.error('摆放设备失败')
  }
}

// 产品字典
const productOptions = ref<IProductsVO[]>([])
// 获取产品下拉框数据
const getProductList = () => {
  getProductsList({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    productOptions.value = res.data.rows || []
  })
}
getProductList()
// 获取产品名称
const getProductName = (productKey) => {
  const product = productOptions.value.find(p => p.productKey === productKey)
  return product ? product.name : ''
}

// 加载背景图片
const loadBackgroundImage = async (ossId) => {
  try {
    const res = await listByIds(ossId)
    if (res && res.code === 200 && res.data && res.data.length > 0) {
      backgroundImage.value = res.data[0].url
    } else {
      backgroundImage.value = ''
    }
  } catch (error) {
    console.error('加载背景图片失败:', error)
    backgroundImage.value = ''
  }
}

onMounted(() => {
  loadBackgroundImage(ossId)
  getDeviceList(id)
})
</script>

<style lang="scss" scoped>
.middle {
  width: 100%;
  height: 100%;
  position: relative;
  > img {
    width: 100%;
  }
}

.device-icon {
  position: absolute;
  transform: translate(-50%, -50%); /* 使设备图标中心点对准指定位置 */
  cursor: pointer;
  z-index: 2;
  
  img {
    width: 32px;
    height: 32px;
    object-fit: contain;
  }
  
  .device-name {
    position: absolute;
    bottom: -20px;
    left: 50%;
    transform: translateX(-50%);
    white-space: nowrap;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    padding: 2px 4px;
    border-radius: 2px;
  }
}

.putting-tip {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  z-index: 10;
  font-size: 14px;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
  
  